<?php
/*
 * Change the password
 */

// read PUT data
parse_str(file_get_contents("php://input"), $put_vars);
if(isset($put_vars['new_password'])&&isset($put_vars['pfa'])&&isset($put_vars['email'])){
	$param = array('1'=>$put_vars['email']);
	
	$pfa = DB::sql("SELECT pfa from user where email = ?", $param);
	$p = $pfa[0]['pfa'];
	// get hasher
	// base-2 logarithm of the iteration count used for password stretching
	$hash_cost_log2 = 8;
	// make hashes non-portable to older systems
	$hash_portable = FALSE;
	// get hasher
	$hasher = new PasswordHash($hash_cost_log2, $hash_portable);
	if (!$hasher->CheckPassword($put_vars['pfa'], $p)) {
		// password does not match
		header('HTTP/1.1 403');
		header("Content-Type: application/json");
		$err = array("error_message" => "Answer is incorrect.  Please try again.");
		echo json_encode($err);
		return;
	}
	
	// hash password
	// base-2 logarithm of the iteration count used for password stretching
	$hash_cost_log2 = 8;
	// make hashes non-portable to older systems
	$hash_portable = FALSE;
	// get hasher
	$hasher = new PasswordHash($hash_cost_log2, $hash_portable);
	$hash = $hasher->HashPassword($put_vars['new_password']);
	if (strlen($hash) < 20)
	{
	// could not hash password
		header('HTTP/1.1 500 Internal Server Error');
		header("Content-Type: application/json");
		$err = array("error_message" => "Internal error.");
		echo json_encode($err);		
		return;
	}
	unset($hasher);
	$param = array('1' => $hash, '2' => $put_vars['email']);
	DB::sql("UPDATE user SET password = ? WHERE email = ?", $param);
	
	header('HTTP/1.1 204');
	header("Content-Type: application/json");
	$response = array('1'=>'Successful');
	echo json_encode($response);
	return;
}

header('HTTP/1.1 500 Internal Server Error');
header("Content-Type: application/json");
$err = array("error_message" => "Password, pfa or email are not inputted");
echo json_encode($err);

?>